package com.yuma.tingshu.live.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yuma.tingshu.common.util.AuthContextHolder;
import com.yuma.tingshu.live.config.LiveProperties;
import com.yuma.tingshu.live.mapper.LiveRoomMapper;
import com.yuma.tingshu.live.service.LiveRoomService;
import com.yuma.tingshu.live.util.LiveUtil;
import com.yuma.tingshu.model.live.LiveRoom;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuma.tingshu.vo.live.LiveRoomVo;
import com.yuma.tingshu.vo.live.TencentLiveAddressVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

	@Autowired
	private LiveRoomMapper liveRoomMapper;

	@Autowired
	private LiveProperties properties;

	@Autowired
	private LiveUtil liveUtil;

	@Override
	public LiveRoom saveLiveRoom(LiveRoomVo liveRoomVo) {

		// 再次查询表中是否存在当前直播的未过期直播间
		LiveRoom liveRoom = this.getOne(new LambdaQueryWrapper<LiveRoom>()
				.eq(LiveRoom::getUserId, AuthContextHolder.getUserId())
				.gt(LiveRoom::getExpireTime, new Date())
				.eq(LiveRoom::getStatus, 1));

		// 有未结束直播间直接返回
		if (liveRoom != null){
			return liveRoom;
		}

		// 新增直播间
		liveRoom = new LiveRoom();
		BeanUtils.copyProperties(liveRoomVo, liveRoom);
		liveRoom.setUserId(AuthContextHolder.getUserId());
		liveRoom.setStatus("1");
		liveRoom.setAppName(properties.getAppName());
		// 腾讯云中的直播间的唯一标识
		String streamName = IdWorker.getIdStr();
		liveRoom.setStreamName(streamName);
		// 生成推流地址和拉流地址
		TencentLiveAddressVo liveAddress = liveUtil.getLiveAddress(streamName, liveRoomVo.getExpireTime().getTime() / 1000);
		liveRoom.setPushUrl(liveAddress.getPushWebRtcUrl());
		liveRoom.setPlayUrl(liveAddress.getPullWebRtcUrl());

		this.liveRoomMapper.insert(liveRoom);

		return liveRoom;
	}
}
